package com.atguigu05.conmunication;
/*
* 生产者(Productor)将产品交给店员(Clerk)，而消费者(Customer)从店员处取走产品，
* 店员一次只能持有固定数量的产品(比如:20)，如果生产者试图生产更多的产品，
* 店员会叫生产者停一下，如果店中有空位放产品了再通知生产者继续生产;
* 如果店中没有产品了、店员会告诉消费者等一下，如果店中有产品了再通知消费者来取走产品。
 * */
public class ProducerAndCustomerTest {
    public static void main(String[] args) {
        Clerk cl=new Clerk();
        Producer p=new Producer(cl);
        Consumer c=new Consumer(cl);
        p.setName("消费者");
        c.setName("生产者");

        p.start();
        c.start();
    }
}

class Clerk{
    private int book;

    public void Add(){
        this.book++;

    }

    public void Min(){
        this.book--;

    }

    public int getBook() {
        return book;
    }

    public void setBook(int book) {
        this.book = book;
    }
    //    private Clerk(){
//
//    }
//    private static Clerk c=new Clerk();
//
//     public static Clerk getInstance() {
//        return c;
//    }

}

class Producer extends Thread{
    private Clerk clerk;    //相同的思路见  03的练习

    public Producer(Clerk clerk){
       this.clerk=clerk;
   }
    @Override
    public void run() {
        while(true){
            synchronized (clerk) {
                if (clerk.getBook()<20) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    clerk.Add();
                    System.out.println("produce"+clerk.getBook());
                }else {
                    System.out.println("已经装满");
                    yield();
                }
            }
        }
    }
}


class Consumer extends Thread{
    private Clerk clerk;

    public Consumer(Clerk clerk){
        this.clerk=clerk;
    }
    @Override
    public void run() {
        while(true){
            synchronized (clerk) {
                if (clerk.getBook()>0) {

                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    clerk.Min();
                    System.out.println("consume"+clerk.getBook());
                }else {
                    System.out.println("已经清空");
                    yield();
                }

            }
        }
    }
}